﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using Library;

namespace TCP_Client
{
    public partial class DangNhap : Form
    {
        public Socket _socketClient;
        public string UserName;
        public DangNhap()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                _socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socketClient.BeginConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888), new AsyncCallback(ConnectCallBack), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void ConnectCallBack(IAsyncResult AR)
        {
            try
            {
                _socketClient.EndConnect(AR);
                ChatMessage chat = new ChatMessage(txtAccount.Text, Command.Login, string.Empty);
                var _buffer = chat.TobyteArray();
                _socketClient.BeginSend(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void SendCallBack(IAsyncResult AR)
        {
            try
            {
                _socketClient.EndSend(AR);
                UserName = txtAccount.Text;
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
